package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.example.mapper.DishBasicMapper;
import org.example.mapper.DishFlavorMapper;
import org.example.model.category.CategoryBasic;
import org.example.model.common.dtos.PageResponseDto;
import org.example.model.common.dtos.category.CategoryBasicDto;
import org.example.model.common.dtos.dish.DishBasicDto;
import org.example.model.common.dtos.dish.DishByCategory;
import org.example.model.dish.DishBasic;
import org.example.model.dish.DishFlavor;
import org.example.service.CategoryBasicService;
import org.example.service.DishBasicService;
import org.example.service.DishFlavorService;
import org.example.service.UserBasicService;
import org.example.utils.PageUtils;
import org.example.utils.UserIdThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Service
@Slf4j
@Transactional
public class DishBasicServiceImpl extends ServiceImpl<DishBasicMapper, DishBasic> implements DishBasicService {

    @Autowired
    private DishBasicMapper dishBasicMapper;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private UserBasicService userBasicService;

    @Autowired
    private CategoryBasicService categoryBasicService;

    /**
     * 新增菜品
     *
     * @param dishBasic
     */
    @Override
    public Boolean InsertDishBasic(DishBasic dishBasic) {
        if (dishBasic == null) return false;
        //获取Token中的数据
        Integer userId = UserIdThreadLocalUtils.getUser();
        if (userId <= 0) return false;
        dishBasic.setStatus(1);
        dishBasic.setCreateUser(userId);
        dishBasic.setCreateDate(LocalDateTime.now());
        dishBasic.setUpdateUser(userId);
        dishBasic.setUpdateDate(LocalDateTime.now());
        //插入菜品基本数据并返回自增主键
        dishBasicMapper.insert(dishBasic);
        int dishId = dishBasic.getId();
        //插入菜品口味列表
        if (dishBasic.getDishFlavors() != null) {
            for (DishFlavor dishFlavor : dishBasic.getDishFlavors()) {
                Boolean flag = dishFlavorService.InsertDishFlavor(dishFlavor,dishId);
                if (!flag) return false;
            }
        }
        return dishId > 0;
    }

    /**
     * 根据id获取菜品详情
     *
     * @param id
     */
    @Override
    public DishBasicDto SelectDishById(int id) {
        if (id <= 0) return new DishBasicDto();
        DishBasic dishBasic = dishBasicMapper.selectById(id);
        if (dishBasic == null) return new DishBasicDto();
        int createId = dishBasic.getCreateUser();
        int updateId = dishBasic.getUpdateUser();
        DishBasicDto dishBasicDto = new DishBasicDto();
        BeanUtils.copyProperties(dishBasic,dishBasicDto);
        dishBasicDto.setCreateUser(userBasicService.SelectUserById(createId).getUsername());
        dishBasicDto.setUpdateUser(userBasicService.SelectUserById(updateId).getUsername());
        dishBasicDto.setDishFlavors(dishFlavorService.SelectFlavorListByDishId(id));
        return dishBasicDto;
    }

    /**
     * 根据条件(菜品名称模糊查询，菜品状态精确查询，菜品分类精确查询)查询菜品列表
     *
     * @param dishBasic
     * @param pageIndex
     * @param pageSize
     */
    @Override
    public PageResponseDto<List<DishBasicDto>> SelectPageByConditions(DishBasic dishBasic, int pageIndex, int pageSize) {
        LambdaQueryWrapper<DishBasic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishBasic::isIsDeleted,false)
                .like(StringUtils.isNotBlank(dishBasic.getDishName()),DishBasic::getDishName,dishBasic.getDishName())
                .eq(dishBasic.getCategoryId() != 0,DishBasic::getCategoryId,dishBasic.getCategoryId())
                .eq(dishBasic.getStatus() != 0,DishBasic::getStatus,dishBasic.getStatus())
                .orderByDesc(DishBasic::getSort)
                .orderByDesc(DishBasic::getCreateDate);
        List<DishBasic> dishBasics = dishBasicMapper.selectList(queryWrapper);
        if (dishBasics.size() == 0) return new PageResponseDto<>();
        List<DishBasicDto> dishBasicDtoList = new ArrayList<>();
        DishBasicDto dishBasicDto = null;
        for (int i = 0; i < dishBasics.size(); i++) {
            dishBasicDto = new DishBasicDto();
            BeanUtils.copyProperties(dishBasics.get(i),dishBasicDto);
            dishBasicDtoList.add(dishBasicDto);
        }
        dishBasicDtoList = dishBasicDtoList.stream().map(item ->{
            item = this.SelectDishById(item.getId());
            return item;
        }).collect(Collectors.toList());
        PageResponseDto<List<DishBasicDto>> pageResponseDto = new PageResponseDto<>();
        pageResponseDto.setSize(dishBasicDtoList.size());
        pageResponseDto.setData(new PageUtils<DishBasicDto>().page(dishBasicDtoList,pageIndex,pageSize));
        return pageResponseDto;
    }

    /**
     * 根据id修改对应菜品信息
     *
     * @param dishBasic
     */
    @Override
    public Boolean UpdateDishBasicById(DishBasic dishBasic) {
        if (dishBasic == null) return false;
        DishBasic dish = dishBasicMapper.selectById(dishBasic.getId());
        if (dish == null) return false;
        //获取Token中的数据
        Integer userId = UserIdThreadLocalUtils.getUser();
        if (userId <= 0) return false;
        dishBasic.setCreateUser(dish.getCreateUser());
        dishBasic.setCreateDate(dish.getCreateDate());
        dishBasic.setUpdateUser(userId);
        dishBasic.setUpdateDate(LocalDateTime.now());
        //清空菜品口味
        dishFlavorService.DeleteFlavorListByDishId(dishBasic.getId());
        //重新添加菜品口味
        if (dishBasic.getDishFlavors() != null) {
            for (DishFlavor dishFlavor : dishBasic.getDishFlavors()) {
                Boolean flag = dishFlavorService.InsertDishFlavor(dishFlavor,dishBasic.getId());
                if (!flag) return false;
            }
        }
        return dishBasicMapper.updateById(dishBasic) > 0;
    }

    /**
     * 根据id删除对应菜品信息
     *
     * @param id
     */
    @Override
    public Boolean DeleteDishBasicById(int id) {
        if (id <= 0) return false;
        DishBasic dishBasic = dishBasicMapper.selectById(id);
        dishBasic.setIsDeleted(true);
        Boolean flag = dishFlavorService.DeleteFlavorListByDishId(dishBasic.getId());
        if (!flag) return false;
        return this.UpdateDishBasicById(dishBasic);
    }

    /**
     * 根据id修改对应菜品信息
     *
     * @param id
     */
    @Override
    public Boolean UpdateStatus(int id) {
        if (id <= 0) return false;
        //获取Token中的数据
        Integer userId = UserIdThreadLocalUtils.getUser();
        if (userId <= 0) return false;
        DishBasic dishBasic = dishBasicMapper.selectById(id);
        dishBasic.setStatus(dishBasic.getStatus() == 1 ? 2 : 1);
        dishBasic.setUpdateUser(userId);
        dishBasic.setUpdateDate(LocalDateTime.now());
        return dishBasicMapper.updateById(dishBasic) > 0;
    }

    /**
     * 批量修改菜品状态
     *
     * @param ids
     * @param type
     */
    @Override
    public Boolean UpdateStatusByIds(int[] ids, int type) {
        if (ids == null || ids.length <= 0) {
            return false;
        }
        //获取Token中的数据
        Integer userId = UserIdThreadLocalUtils.getUser();
        if (userId <= 0) return false;
        for (Integer id : ids) {
            DishBasic dishBasic = dishBasicMapper.selectById(id);
            dishBasic.setStatus(type);
            dishBasic.setUpdateUser(userId);
            dishBasic.setUpdateDate(LocalDateTime.now());
            Boolean flag = dishBasicMapper.updateById(dishBasic) > 0;
            if (!flag) return false;
        }
        return true;
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    public Boolean DeleteDishBasicByIds(int[] ids) {
        if (ids == null || ids.length <= 0) {
            return false;
        }
        //获取Token中的数据
        Integer userId = UserIdThreadLocalUtils.getUser();
        if (userId <= 0) return false;
        for (Integer id : ids) {
            Boolean flag = this.DeleteDishBasicById(id);
            if (!flag) return false;
        }
        return true;
    }

    /**
     * 获取不同分类下菜品数据
     */
    @Override
    public List<DishByCategory> SelectDishListByCategory() {
        CategoryBasic categoryBasic = new CategoryBasic();
        categoryBasic.setType(1);
        List<CategoryBasicDto> categoryBasicDtoList = categoryBasicService.SelectPageByConditions(categoryBasic, 1, 100).getData();
        List<DishByCategory> dishByCategories = new ArrayList<>();
        DishByCategory dishByCategory = null;
        DishBasic dishBasic = null;
        for (CategoryBasicDto categoryBasicDto : categoryBasicDtoList) {
            dishByCategory = new DishByCategory();
            BeanUtils.copyProperties(categoryBasicDto,dishByCategory);
            dishBasic = new DishBasic();
            dishBasic.setCategoryId(categoryBasicDto.getId());
            List<DishBasicDto> dishBasicDtos = this.SelectPageByConditions(dishBasic, 1, 1000).getData();
            dishByCategory.setDishList(dishBasicDtos);
            dishByCategories.add(dishByCategory);
        }
        return dishByCategories;
    }
}
